package com.lzq.chatroom_project.model;

import com.lzq.chatroom_project.common.utils.CacheUtil;
import com.lzq.chatroom_project.common.utils.JacksonUtil;
import com.lzq.chatroom_project.dao.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

import static com.lzq.chatroom_project.common.constants.CacheKeyConstants.ONLINE_USER_INFO_KEY;

@Slf4j
@Component
public class OnlineUserManager {
    //记录下在线的userId和webSocketSession的映射关系
    private ConcurrentHashMap<Integer, WebSocketSession> sessions = new ConcurrentHashMap<>();
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private UserMapper userMapper;


    /**
     * 记录用户上线
     * @param userId
     * @param session
     */
    public void online(int userId, WebSocketSession session) {
        if (sessions.get(userId) != null) {
            return;
        }
        sessions.put(userId, session);
        if (!cacheUtil.hasKey(ONLINE_USER_INFO_KEY + userId)) {
            User userInfo = userMapper.selectUserById(userId);
            cacheUtil.set(ONLINE_USER_INFO_KEY + userId, JacksonUtil.writeValueAsString(userInfo));
        }
        log.info("用户:userId:{}上线", userId);
    }

    /**
     * 记录用户下线
     * @param userId
     * @param session
     */
    public void offline(int userId, WebSocketSession session) {
        WebSocketSession existSession = sessions.get(userId);
        if (existSession != session) {
            return;
        }
        sessions.remove(userId);
        log.info("用户:userId:{}下线", userId);
    }

    /**
     * 获取用户的webSocketSession
     * @param userId
     * @return
     */
    public WebSocketSession getSession(int userId) {
        return sessions.get(userId);
    }
}

